# coding:utf-8

import re
import json
import urllib

from tld import get_tld

from app.codes import SUCCESS


class ApiResponse(object):
    def __new__(cls, code=SUCCESS, body=None):
        return json.dumps(
            {
                'code': code.code,
                'message': code.msg,
                'body': body
            }
        ), code.http_code


class _Command(object):

    def __init__(self, producer):
        self.producer = producer

    def __getattr__(self, item):
        self.func = item
        return self

    def __call__(self, *args, **kwargs):
        body = dict(
            func=self.func,
            args=args,
            kwargs=kwargs
        )
        self.producer.send(json.dumps(body))


class MsgProxy(object):
    """
    create by ld_wu 2017-11-27
    消息发送代理（目前只有im message的消费者实现了）
    """

    def __getattribute__(self, item):
        from flask import current_app
        return _Command(getattr(current_app, item, None))


def get_root_host_name(url):
    """
    created by chenhj at 2018/5/23
    根据url获取根域名
    传入 https://pc.hostname.com
    返回 hostname.com

    若根域名为wanpinghui.com等6个域名, 则直接返回(手机站的话需要取消m.)
    """
    url = url or 'https://www.wanpinghui.com'
    r = r'(.*)(wanpinghui.com|wanpingwang.com|maipingba.com|yongpingba.com|wanpingfa.com|dapinghui.com)'
    if re.search(r, url):
        url = urllib.parse.urlsplit(url).netloc
        if url.startswith('m.'):
            return url.replace('m.', '')
        else:
            return url
    return get_tld(url)
